<template>
  <div class="hospital-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h3>医院管理</h3>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form :model="searchForm" inline>
            <el-form-item label="医院名称">
              <el-input
                  v-model="searchForm.name"
                  placeholder="请输入医院名称"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增医院
          </el-button>
          <el-button
              type="danger"
              :disabled="selectedHospitals.length === 0"
              @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedHospitals.length }})
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-number">{{ pagination.total }}</div>
            <div class="stat-label">总医院数</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-number">{{ selectedHospitals.length }}</div>
            <div class="stat-label">已选择</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-number">{{ hospitalList.length }}</div>
            <div class="stat-label">当前页</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 医院表格 -->
    <div class="table-section">
      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="hospitalList"
          @selection-change="handleSelectionChange"
          stripe
          border
          style="width: 100%"
          empty-text="暂无医院数据"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="name" label="医院名称" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
                title="确定要删除这个医院吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                    type="danger"
                    size="small"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 医院对话框 -->
    <HospitalDialog
        v-model:visible="dialogVisible"
        :hospital-data="currentHospital"
        :is-edit="isEdit"
        @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'
import { hospitalApi } from '../api/hospital'
import HospitalDialog from '../components/HospitalDialog.vue'

// 响应式数据
const loading = ref(false)
const hospitalList = ref([])
const selectedHospitals = ref([])
const tableRef = ref()

const dialogVisible = ref(false)
const currentHospital = ref({})
const isEdit = ref(false)

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const searchForm = reactive({
  name: ''
})

// 获取医院列表
const getHospitalList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await hospitalApi.getHospitalList(params)
    hospitalList.value = response.records || response.list || []
    pagination.total = response.total || 0

  } catch (error) {
    console.error('获取医院列表失败:', error)
    ElMessage.error('获取医院列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getHospitalList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: ''
  })
  pagination.current = 1
  getHospitalList()
}

// 新增医院
const handleAdd = () => {
  currentHospital.value = {}
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑医院
const handleEdit = (row) => {
  currentHospital.value = { ...row }
  isEdit.value = true
  dialogVisible.value = true
}

// 删除医院
const handleDelete = async (row) => {
  try {
    await hospitalApi.deleteHospital(row.id)
    ElMessage.success('删除成功')
    getHospitalList()

  } catch (error) {
    console.error('删除医院失败:', error)
    ElMessage.error('删除医院失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedHospitals.value.length === 0) {
    ElMessage.warning('请选择要删除的医院')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedHospitals.value.length} 个医院吗？此操作不可恢复！`,
        '批量删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
    )

    const ids = selectedHospitals.value.map(hospital => hospital.id)
    await hospitalApi.batchDeleteHospitals(ids)
    ElMessage.success(`成功删除 ${selectedHospitals.value.length} 个医院`)
    getHospitalList()

  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedHospitals.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getHospitalList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  pagination.current = current
  getHospitalList()
}

// 对话框成功回调
const handleDialogSuccess = () => {
  getHospitalList()
}

// 组件挂载时获取数据
onMounted(() => {
  getHospitalList()
})
</script>

<style scoped>
.hospital-list-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.text-right {
  text-align: right;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section .el-col {
    margin-bottom: 10px;
  }

  .text-right {
    text-align: left;
  }

  .el-table {
    font-size: 12px;
  }

  .stats-section .el-col {
    margin-bottom: 10px;
  }
}
</style>
